import pymysql, os, pytest
from path.path import Path
from read.read_yaml import Read_yaml
import pytest
from config.Readconfig import Read_config
from ERRO.erro import *
from log.log import Log
confnig=Read_config().mysql
path=Path()
log=Log()


def pytest_addoption(parser):
    """注册命令"""
    parser.addoption(
        '--file_name',
        action='store',
        default=None,
        help="此方法用于命令执行.yaml文件"
    )


def file_name(name):
    """收集yaml文件名称"""
    file_data = []
    if name:
        file_data.append(Read_yaml(name).read)
    else:
        file_list = os.listdir(os.path.join(path.root_path, 'data'))
        for name in file_list:
            file_data.append(Read_yaml(name).read)
    return file_data


def List_processing(name):
    """将每个test分离到列表中"""
    test_data = []
    for value in file_name(name):
        for test_key, test_value in value.items():
            test_dict = {}
            test_dict[test_key] = test_value
            test_data.append(test_dict)

    return test_data


def pytest_generate_tests(metafunc):
    """自定义数据驱动"""
    name = []
    filename = metafunc.config.option.file_name
    for i in List_processing(filename):
        #得到用例名字
        for key in i.keys():
            name.append(key)
    if "parma" in metafunc.fixturenames:
        metafunc.parametrize('parma', List_processing(filename),
                             ids=[i for i in name],
                             scope="function")
    else:
        raise Exception("用例当中参数不是parma")


def pytest_runtest_logstart(nodeid, location):
    """获取开始执行的.py路径"""
    global current_id
    current_id = nodeid

def db_restore(config_sql, database, test_env=True):
    if test_env:
        db = "mcrtestenv.sql"
    else:
        db = "original_db.sql"
    connect = pymysql.connect(host=config_sql["host"], port=config_sql["port"], user=config_sql["user"],
                              password=config_sql["password"], database=database)
    cursor = connect.cursor()

    try:
        with open(db, encoding='utf-8', mode='r') as f:
            sql_list = f.readlines()
            sql_clean_list = []
            for x in sql_list:
                x = x.strip()
                if x.startswith("--") or x.startswith("/*") or x == "":
                    continue
                sql_clean_list.append(x)
            sql_clean_list = "".join(sql_clean_list).split(";")[:-1]    # to avoid last empty guy
            for x in sql_clean_list:
                sql_item = x + ";"
                cursor.execute(sql_item)
                log.sql_implement(sql_item)
    except Exception as e:
        if test_env:
            log.log.error("Setup test environment failed.")
        else:
            log.log.error("Restore original environment failed.")
        log.log.error(e)
    finally:
        log.log.info("DB restoration finished.")
        cursor.close()
        connect.commit()
        connect.close()


@pytest.fixture(autouse=True)
def wlog():
    with open(os.path.join(path.root_path, 'log//log.txt'), 'a+', encoding='utf-8') as f:
        f.write("\n" + '-' * 50 + '开始测试' + current_id + '-' * 50 + '\n')
    yield
    with open(os.path.join(path.root_path, 'log//log.txt'), 'a+', encoding='utf-8') as f:
        f.write('-' * 50 + '结束测试' + current_id + '-' * 50 + '\n')


# @pytest.fixture(scope='class', autouse=True)
# def add_test_databse():
#     database = "mcr"
#     config_sql = Read_config().mysql
#
#     dump_database = "mysqldump -h{0} -P{1} -u{2} -p{3} {4} > {5} --default_character-set=utf8".format(
#         config_sql["host"], config_sql["port"], config_sql["user"], config_sql["password"], database, "original_db.sql")
#     if os.system(dump_database) == 0:
#         log.log.info("DB backup successfully.")
#         log.log.info("DB file: original_db.sql.")
#
#     else:
#         log.log.error("DB backup failed. " + dump_database)
#         raise db_error
#     db_restore(config_sql, database)
#     yield
#     db_restore(config_sql, database, test_env=False)




